package actions;

import java.sql.*;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.RowSet;

import model.ReviewerModel;
import model.StudentModel;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DbException;

public class ViewAnalyticsAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws DbException {
        // get analtyic choice from request scope
        String choice = (String)request.getSession(false).getAttribute("choice");
        // get category
        String category = request.getParameter("category");
        // Result set storing all the applications
        ResultSet  application = null;
        // arraylist of grades
        ArrayList<Integer> grades = new ArrayList<Integer>();
        ArrayList<Double>  averageGrades = new ArrayList<Double>();
        // average of all the grades
        double average = 0;

        
        // store discipline application in request object
        if(choice.equals("discipline")){
            application = ReviewerModel.getApplicationsByDiscipline(category);
        }else if(choice.equals("specialization")){
            // store specialization applications
            application = ReviewerModel.getApplicationsBySpecialization(category);
        }

        // for every application
        try {
            while(application.next()){
                average = 0;
                // get the student id
                int studentid = application.getInt("pid");
                // get the grades of that student
                grades = StudentModel.getAllStudentGrades(studentid);
                // calculate average
                for(int i = 0; i < grades.size(); i++){
                    average += grades.get(i);
                }
                average = (double)average/grades.size();
                // store average
                averageGrades.add(average);
            }
            application.beforeFirst();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        // store grades into request object
        request.getSession(false).setAttribute("grades", averageGrades);

        // store applications into request object
        request.getSession(false).setAttribute("application", application);
        return mapping.findForward("success");
    }
}
